const http = require('http');
const fs = require('fs');
const path = require('path');

const port = 3000;

// MIME类型映射
const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml',
    '.wav': 'audio/wav',
    '.mp4': 'video/mp4',
    '.woff': 'application/font-woff',
    '.ttf': 'application/font-ttf',
    '.eot': 'application/vnd.ms-fontobject',
    '.otf': 'application/font-otf',
    '.wasm': 'application/wasm'
};

const server = http.createServer((req, res) => {
    console.log(`${req.method} ${req.url}`);
    
    // 设置CORS头
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    
    if (req.method === 'OPTIONS') {
        res.writeHead(200);
        res.end();
        return;
    }
    
    let filePath = '.' + req.url;
    if (filePath === './') {
        filePath = './index.html';
    }
    
    const extname = String(path.extname(filePath)).toLowerCase();
    const mimeType = mimeTypes[extname] || 'application/octet-stream';
    
    fs.readFile(filePath, (error, content) => {
        if (error) {
            if (error.code === 'ENOENT') {
                // 文件未找到
                res.writeHead(404, { 'Content-Type': 'text/html' });
                res.end(`
                    <!DOCTYPE html>
                    <html>
                    <head>
                        <title>404 - 文件未找到</title>
                        <style>
                            body { 
                                font-family: Arial, sans-serif; 
                                text-align: center; 
                                padding: 50px;
                                background: linear-gradient(135deg, #1e3c72, #2a5298);
                                color: white;
                            }
                            .container {
                                max-width: 600px;
                                margin: 0 auto;
                                background: rgba(0,0,0,0.3);
                                padding: 40px;
                                border-radius: 10px;
                            }
                            h1 { color: #ff6b6b; }
                            a { color: #4ecdc4; text-decoration: none; }
                            a:hover { text-decoration: underline; }
                        </style>
                    </head>
                    <body>
                        <div class="container">
                            <h1>404 - 页面未找到</h1>
                            <p>请求的文件 <code>${req.url}</code> 不存在。</p>
                            <p><a href="/">返回首页</a></p>
                        </div>
                    </body>
                    </html>
                `, 'utf-8');
            } else {
                // 服务器错误
                res.writeHead(500);
                res.end(`服务器错误: ${error.code}`);
            }
        } else {
            // 成功返回文件
            res.writeHead(200, { 'Content-Type': mimeType });
            res.end(content, 'utf-8');
        }
    });
});

server.listen(port, () => {
    console.log(`\n🚀 Three.js 完整教程服务器已启动!`);
    console.log(`📍 本地地址: http://localhost:${port}`);
    console.log(`📁 服务目录: ${__dirname}`);
    console.log(`\n💡 功能特性:`);
    console.log(`   • 完整的 Three.js 开发流程演示`);
    console.log(`   • 5种不同场景模式`);
    console.log(`   • 实时交互和动画效果`);
    console.log(`   • 性能监控和调试工具`);
    console.log(`   • 后处理效果演示`);
    console.log(`\n🎮 控制说明:`);
    console.log(`   • 鼠标: 旋转/平移/缩放视角`);
    console.log(`   • 点击: 选中物体高亮`);
    console.log(`   • 键盘 1-5: 切换场景`);
    console.log(`   • 空格: 开启/关闭自动旋转`);
    console.log(`\n按 Ctrl+C 停止服务器\n`);
});

// 优雅关闭
process.on('SIGINT', () => {
    console.log('\n👋 正在关闭服务器...');
    server.close(() => {
        console.log('✅ 服务器已关闭');
        process.exit(0);
    });
});